package com.ruyuan.payment.server.alipay;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradeRefundRequest;
import com.alipay.easysdk.factory.Factory;
import com.alipay.easysdk.kernel.util.ResponseChecker;
import com.alipay.easysdk.payment.common.models.*;
import com.alipay.easysdk.payment.page.models.AlipayTradePagePayResponse;
import com.ruyuan.payment.server.exception.BusinessException;
import com.ruyuan.payment.server.exception.BusinessExceptionEnum;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Service
public class AliPayService {

    private static final Logger LOG = LoggerFactory.getLogger(AliPayService.class);

    @Resource
    private AliPayProperties aliPayProperties;

    @Resource
    private AliPayConfig aliPayConfig;

    public AlipayTradePagePayResponse pay(String subject, String outTradeNo, String totalAmount) {
        // 1. 设置参数（全局只需设置一次）
        Factory.setOptions(aliPayConfig.getOptions());
        try {
            // 2. 发起API调用（以创建网站支付为例）
            AlipayTradePagePayResponse response = Factory.Payment.Page()
                    .pay(subject, outTradeNo, totalAmount, aliPayProperties.getReturnUrl());
            // 3. 处理响应或异常
            if (ResponseChecker.success(response)) {
                LOG.info("调用支付宝下单接口成功，结果：{}", JSON.toJSONString(response));
                return response;
            } else {
                LOG.warn("调用支付宝下单接口失败，原因：{}", JSON.toJSONString(response));
                throw new BusinessException(BusinessExceptionEnum.ALIPAY_ERROR);
            }
        } catch (Exception e) {
            LOG.error("调用支付宝下单接口异常，原因：", e);
            throw new BusinessException(BusinessExceptionEnum.ALIPAY_ERROR);
        }
    }

    public AlipayTradeQueryResponse query(String outTradeNo) {
        Factory.setOptions(aliPayConfig.getOptions());
        try {
            AlipayTradeQueryResponse response = Factory.Payment.Common().query(outTradeNo);
            if (ResponseChecker.success(response)) {
                LOG.info("调用支付宝订单查询接口成功，结果：{}", JSON.toJSONString(response));
                return response;
            } else {
                LOG.warn("调用支付宝订单查询接口失败，原因：{}", JSON.toJSONString(response));
                // throw new BusinessException(BusinessExceptionEnum.ALIPAY_ERROR);
                return response;
            }
        } catch (Exception e) {
            LOG.error("调用支付宝订单查询接口异常，原因：", e);
            throw new BusinessException(BusinessExceptionEnum.ALIPAY_ERROR);
        }
    }

    public AlipayTradeCloseResponse close(String outTradeNo) {
        Factory.setOptions(aliPayConfig.getOptions());
        try {
            AlipayTradeCloseResponse response = Factory.Payment.Common().close(outTradeNo);
            if (ResponseChecker.success(response)) {
                LOG.info("调用支付宝关闭订单接口成功，结果：{}", JSON.toJSONString(response));
                return response;
            } else {
                LOG.warn("调用支付宝关闭订单接口失败，原因：{}", JSON.toJSONString(response));
                // throw new BusinessException(BusinessExceptionEnum.ALIPAY_ERROR);
                return response;
            }
        } catch (Exception e) {
            LOG.error("调用支付宝关闭订单接口异常，原因：", e);
            throw new BusinessException(BusinessExceptionEnum.ALIPAY_ERROR);
        }
    }

    public AlipayTradeRefundResponse refund(String outTradeNo, String refundAmount) {
        Factory.setOptions(aliPayConfig.getOptions());
        try {
            AlipayTradeRefundResponse response = Factory.Payment.Common().refund(outTradeNo, refundAmount);
            if (ResponseChecker.success(response)) {
                LOG.info("调用支付宝退款接口成功，结果：{}", JSON.toJSONString(response));
                return response;
            } else {
                LOG.warn("调用支付宝退款接口失败，原因：{}", JSON.toJSONString(response));
                // throw new BusinessException(BusinessExceptionEnum.ALIPAY_ERROR);
                return response;
            }
        } catch (Exception e) {
            LOG.error("调用支付宝退款接口异常，原因：", e);
            throw new BusinessException(BusinessExceptionEnum.ALIPAY_ERROR);
        }
    }

    public com.alipay.api.response.AlipayTradeRefundResponse refundPart(String outTradeNo, String refundAmount, String refundRequestNo) {
        Factory.setOptions(aliPayConfig.getOptions());
        try {
            AlipayClient alipayClient = new DefaultAlipayClient(
                    aliPayProperties.getGatewayHttpsHost(),
                    aliPayProperties.getAppId(),
                    aliPayProperties.getMerchantPrivateKey(),
                    "json",
                    "GBK",
                    aliPayProperties.getAlipayPublicKey(),
                    "RSA2");
            AlipayTradeRefundRequest request = new AlipayTradeRefundRequest();
            JSONObject bizContent = new JSONObject();
            bizContent.put("out_trade_no", outTradeNo);
            bizContent.put("refund_amount", refundAmount);
            bizContent.put("out_request_no", refundRequestNo);

            //// 返回参数选项，按需传入
            //JSONArray queryOptions = new JSONArray();
            //queryOptions.add("refund_detail_item_list");
            //bizContent.put("query_options", queryOptions);

            request.setBizContent(bizContent.toString());
            com.alipay.api.response.AlipayTradeRefundResponse response = alipayClient.execute(request);
            if(response.isSuccess()){
                LOG.info("调用支付宝部分退款接口成功，结果：{}", JSON.toJSONString(response));
                return response;
            } else {
                LOG.warn("调用支付宝部分退款接口失败，原因：{}", JSON.toJSONString(response));
                // throw new BusinessException(BusinessExceptionEnum.ALIPAY_ERROR);
                return response;
            }
        } catch (Exception e) {
            LOG.error("调用支付宝部分退款接口异常，原因：", e);
            throw new BusinessException(BusinessExceptionEnum.ALIPAY_ERROR);
        }
    }

    public AlipayTradeFastpayRefundQueryResponse queryRefund(String outTradeNo, String outRequestNo) {
        Factory.setOptions(aliPayConfig.getOptions());
        try {
            AlipayTradeFastpayRefundQueryResponse response = Factory.Payment.Common().queryRefund(outTradeNo, outRequestNo);
            if (ResponseChecker.success(response)) {
                LOG.info("调用支付宝退款查询接口成功，结果：{}", JSON.toJSONString(response));
                return response;
            } else {
                LOG.warn("调用支付宝退款查询接口失败，原因：{}", JSON.toJSONString(response));
                return response;
            }
        } catch (Exception e) {
            LOG.error("调用支付宝退款查询接口异常，原因：", e);
            throw new BusinessException(BusinessExceptionEnum.ALIPAY_ERROR);
        }
    }

    public AlipayDataDataserviceBillDownloadurlQueryResponse downloadBill(String billDate) {
        Factory.setOptions(aliPayConfig.getOptions());
        try {
            AlipayDataDataserviceBillDownloadurlQueryResponse response = Factory.Payment.Common().downloadBill("signcustomer", billDate);
            if (ResponseChecker.success(response)) {
                LOG.info("调用支付宝下载账单接口成功，结果：{}", JSON.toJSONString(response));
                return response;
            } else {
                LOG.warn("调用支付宝下载账单接口失败，原因：{}", JSON.toJSONString(response));
                return response;
            }
        } catch (Exception e) {
            LOG.error("调用支付宝下载账单接口异常，原因：", e);
            throw new BusinessException(BusinessExceptionEnum.ALIPAY_ERROR);
        }
    }
}
